//引入koa
const Koa = require("koa")
//引入db （mongoose文件）
const db = require("./db")
//引入 koa-body 用来解析参数
const { koaBody } = require("koa-body")
//解决跨域问题的中间件
const cors = require("koa2-cors")
//引入生成token的中间件
const jwt = require('jsonwebtoken')
//创建koa-router对象
const Router = require('@koa/router')
const router = new Router()
//初始化 链接mongoose
db.init()
//创建koa对象
const app = new Koa()
app.use(cors())
app.use(koaBody())
app.use(router.routes())
//登录
router.post("/login", async (ctx, next) => {
  const { username, password } = ctx.request.body
  console.log(username, password, "koa")
  //调用db的方法 对用户名和密码进行校验
  let isPass = await db.checkUser(username, password)
  if (isPass) {
    //生成token
    let token = jwt.sign({ username }, "2302B")
    //响应回前端
    ctx.body = {
      success: true,
      msg: "登录成功",
      data: {
        token
      }
    }
  } else {
    //响应错误信息
    ctx.body = {
      success: false,
      msg: "登录失败,用户名或密码错误",
    }
  }
})
//注册
router.post("/register",async (ctx,next)=>{
  const {username,password} = ctx.request.body
  console.log(username,password);
  let res = await db.registerUser(username,password)
  if(res){
    ctx.body = {
      success:true,
      msg:"注册成功"
    }
  }else {
    ctx.body = {
      success:false,
      msg:"该用户已被注册"
    }
  }
})
//删除
router.post("/del",async (ctx)=>{
  const {id} = ctx.request.body
  let res = await db.delItem(id)
  ctx.body = res
})
//查找数据
router.post("/find",async (ctx)=>{
  const {id} = ctx.request.body
  console.log(id,"我是查询ID")
  let res = await db.findItem(id)
  console.log(res,"我是查询返回值")
  ctx.body = res
})
//获取全部数据
router.get("/home",async (ctx)=>{
  let res = await db.getList()
  
  ctx.body = {
    data:res
  }
})
//修改数据
router.post("/edit",async (ctx)=>{
  const {id,obj} = ctx.request.body
  await db.edit(id,obj)
  ctx.body = 1
})
app.listen(8000, () => {
  console.log("服务器8000端口启动成功")
})





